import { reactive } from 'vue'

// 定义服务的状态
interface WebSocketState {
  isConnected: boolean;
  error: Event | null;
}

class WebSocketAudioService {
  private socket: WebSocket | null = null;
  private url: string = '';
  // 使用 Vue 的 reactive 来让状态变化能够被组件观察到
  public state = reactive<WebSocketState>({
    isConnected: false,
    error: null,
  });
  
  // 存储音频数据回调函数
  private onAudioDataCallback: ((data: ArrayBuffer) => void) | null = null;

  // 连接方法
  public connect(url: string): void {
    // 如果已经连接或正在连接，则不执行任何操作
    if (this.socket && (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING)) {
      console.log('WebSocket is already connected or connecting.');
      return;
    }
    
    this.url = url;
    console.log('Attempting to connect to WebSocket...');
    this.socket = new WebSocket(this.url);

    this.socket.binaryType = 'arraybuffer';

    this.socket.onopen = () => {
      console.log('WebSocket audio stream connection established.');
      this.state.isConnected = true;
      this.state.error = null;
    };

    this.socket.onmessage = (event) => {
      // 确认是音频流数据
      if (event.data instanceof ArrayBuffer) {
        if (this.onAudioDataCallback) {
          this.onAudioDataCallback(event.data);
        }
      }
    };

    this.socket.onclose = (event) => {
      console.log('WebSocket audio stream connection closed:', event.code, event.reason);
      this.state.isConnected = false;
      // 除非是正常关闭，否则尝试重连
      if (!event.wasClean) {
        console.log('Connection died, attempting to reconnect in 3 seconds...');
        setTimeout(() => this.connect(this.url), 3000);
      }
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket audio stream error:', error);
      this.state.isConnected = false;
      this.state.error = error;
    };
  }
  
  // 注册处理音频数据的回调
  public onAudioData(callback: (data: ArrayBuffer) => void): void {
    this.onAudioDataCallback = callback;
  }

  // 断开连接方法
  public disconnect(): void {
    if (this.socket) {
      console.log('Closing WebSocket connection deliberately.');
      this.socket.close(1000, 'Client disconnected'); // 1000 表示正常关闭
      this.socket = null;
      this.state.isConnected = false;
    }
  }
}

// 导出单例实例
export const webSocketAudioService = new WebSocketAudioService();